package noema.interceptor;

import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;

import org.apache.log4j.Logger;

public class LoggerInterceptor {

	private Logger log;

	public LoggerInterceptor() {
		log = Logger.getLogger(LoggerInterceptor.class);
	}

	@AroundInvoke
	public Object loggerMethod(InvocationContext ctx) throws Exception {
		StringBuffer logString = new StringBuffer();
		logString.append(ctx.getTarget().getClass().getName());
		logString.append(".");
		logString.append(ctx.getMethod().getName());
		logString.append("(");
		if (ctx.getParameters().length > 0) {
			for (int i = 0; i < ctx.getParameters().length - 1; i++) {
				logString.append(ctx.getParameters()[i] + ",");
			}
			logString
					.append(ctx.getParameters()[ctx.getParameters().length - 1]);
		}
		logString.append(")");
		log.info("invoking "+logString+"...");
		
		long startT = System.currentTimeMillis();
		Object obj = ctx.proceed();
		long endT = System.currentTimeMillis();
		
		if(obj!=null){
			logString.append("="+obj);
		}
		log.info("..."+logString+" executed in "+(endT-startT)+"ms");
		return obj;
	}
}
